package com.ykh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ykh.mapper.VideoMapper;
import com.ykh.pojo.dto.PageParams;
import com.ykh.pojo.po.CollectUserVideo;
import com.ykh.mapper.CollectUserVideoMapper;
import com.ykh.pojo.po.Video;
import com.ykh.pojo.vo.Result;
import com.ykh.pojo.vo.VideoVo;
import com.ykh.service.CollectUserVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ykh.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ykh
 * @since 2023年10月26日
 */
@Service
public class CollectUserVideoServiceImpl extends ServiceImpl<CollectUserVideoMapper, CollectUserVideo> implements CollectUserVideoService {

    @Autowired
    CollectUserVideoMapper collectUserVideoMapper;

    @Autowired
    VideoServiceImpl videoServiceImpl;

    @Autowired
    VideoMapper videoMapper;
    /**
     * 用户收藏视频
     * @param videoId
     * @return
     */
    @Override
    public Result collect(Integer videoId, String account) {
        LambdaQueryWrapper<CollectUserVideo> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Video> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper.eq(CollectUserVideo::getVideoId, videoId).eq(CollectUserVideo::getUserId, account);
        CollectUserVideo collectUserVideo = collectUserVideoMapper.selectOne(queryWrapper);
        if(collectUserVideo != null){
            return Result.fail(405,"已收藏过该作品");
        }
        CollectUserVideo collectUserVideo1 = new CollectUserVideo();
        collectUserVideo1.setVideoId(videoId);
        collectUserVideo1.setUserId(account);
        collectUserVideoMapper.insert(collectUserVideo1);

        //对应视频的收藏量+1
        queryWrapper1.eq(Video::getVideoId, videoId);
        Video video = videoMapper.selectOne(queryWrapper1);
        video.setCollectNum(video.getCollectNum()+1);
        videoMapper.update(video,queryWrapper1);
        return Result.success("收藏成功");
    }

    /**
     * 分页查询用户收藏视频
     * @param
     * @return
     */
    @Override
    public List<VideoVo> collectList(PageParams pageParams, String account) {
        int page = pageParams.getPage();
        int pageSize = pageParams.getPageSize();
        //计算偏移量
        int offset = (page-1) * pageSize;
        String condition = pageParams.getCondition();
        //查询该数据库的
        List<Video> videoList = collectUserVideoMapper.findVideoByUser(pageSize, offset, condition, account);
        List<VideoVo> videoVoList = videoServiceImpl.copyList(videoList);
        return videoVoList;
    }
}
